﻿namespace ElisVK.Data
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.IO;
    using System.Linq;
    using System.Xml;

    class GroupInfo : IComparable
    {
        public int GroupID { get; set; }

        public string Name { get; set; }


        public GroupInfo() {}

        public GroupInfo(DataRow dataRow)
        {
            if (dataRow.Table.Columns.Contains("gid"))
                GroupID = int.Parse(dataRow["gid"].ToString());

            if (dataRow.Table.Columns.Contains("name"))
                Name = dataRow["name"].ToString();
        }

        public static List<GroupInfo> ParseUserInfosFromXML(string data)
        {
            var groupInfos = new List<GroupInfo>();

            if (string.IsNullOrEmpty(data))
                return groupInfos;

            var xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(data);

            if (xmlDocument.ChildNodes.Cast<XmlNode>().Any(node => node.Name == "error"))
            {
                return groupInfos;
            }

            var dataSet = new DataSet();

            dataSet.ReadXml(new StringReader(xmlDocument.InnerXml), XmlReadMode.InferSchema);

            if (dataSet.Tables["group"] != null && dataSet.Tables["group"].Rows.Count > 0)
            {
                foreach (DataRow dataRow in dataSet.Tables["group"].Rows)
                {
                    groupInfos.Add(new GroupInfo(dataRow));
                }
            }

            return groupInfos;
        }

        public override string ToString()
        {
            return Name;
        }

        public int CompareTo(object obj)
        {
            var userInfo = obj as UserInfo;

            if (userInfo == null) 
                return -1;

            return ToString().CompareTo(userInfo.ToString());
        }
    }
}
